package com.ydd.controller.user;

import com.ydd.dto.IndexLoginDTO;
import com.ydd.entity.YddUser;
import com.ydd.properties.JwtProperties;
import com.ydd.result.Result;
import com.ydd.service.indexSever;
import com.ydd.utils.JwtUtil;
import com.ydd.vo.TokenVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description TODO
 * @Author itheima
 * @Date 2023-05-03 11:17
 */
@Api(tags = "前台登录接口")
@Slf4j
@RestController
@RequestMapping("/home/index")
public class IndexLoginController {

    @Autowired
    private  indexSever indexSever;
    @Autowired
    private JwtProperties jwtProperties; //涉及Bean

    //完成登录页面实现跳转主页
    @ApiOperation("登陆接口")
    @PostMapping("/login")
    public Result<TokenVo> login(@RequestBody IndexLoginDTO indexLoginDTO) {
        log.info("登录：{}",indexLoginDTO);
        YddUser user= indexSever.login(indexLoginDTO);

        if (user == null){
            return Result.error("用户名或密码错误");
        }

        Map<String, Object> claims = new HashMap<>();
        claims.put("userId",user.getId());


        String token = JwtUtil.createJWT(
                jwtProperties.getUserSecretKey(),
                jwtProperties.getAdminTtl(),
                claims
        );
        TokenVo tokenVo=new TokenVo();
        tokenVo.setToken(token);

        //返回token
        return Result.success(tokenVo);
    }
}
